package com.fs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.mapper.ItemDescMapper;
import com.fs.mapper.ItemMapper;
import com.fs.pojo.Item;
import com.fs.pojo.ItemDesc;
import com.fs.vo.ItemVo;
import com.fs.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    /**
     * sql:select * from item limt 起始位置，显示条数
     * 参数说明：
     *      1.page用来封装分页参数，第几条/每页多少条
     *      2.
     */
    @Override
    public PageResult getItemList(PageResult pageResult) {
        //1.构建模糊查询
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(flag,"title",pageResult.getQuery());
        //定义分页对象
        Page<Item> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        page = itemMapper.selectPage(page, queryWrapper);//2+2
        long total = page.getTotal();//获取总数
        List<Item> rows = page.getRecords();//获取分页的结果
        return pageResult.setTotal(total).setRows(rows);
    }

    /**
     * 需求：完成2部分的入库操作
     * 1.完成item的入库操作
     * 2.完成itemdesc的入库操作  item.id=itemdesc.id
     */
    @Override
    @Transactional
    public void saveItem(ItemVo itemVo) {
        //1.实现ite对象的入库
        Item item = itemVo.getItem().setStatus(true);
        itemMapper.insert(item);
        //2.实现itemDesc对象的入库
        ItemDesc itemDesc = itemVo.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
       itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }

}
